<template>
  <div>
    <page-layout>
      <a-row :gutter="[10, 10]">
        <a-col :span="24">
          <a-card>
            <footer-button :buttons="state.buttons" />
            <a-form ref="formRef" :model="state.formState" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-form-item :label="t('message-manage.label.image')"
                           name="coverPicture"
                           :rules="{required: true, message: t('message-manage.message.pleaseUpload'), trigger: 'blur'}"
              >
                <a-upload
                  name="avatar"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  action="#"
                  :before-upload="beforeUpload"
                >
                  <a-spin :spinning="state.uploadImgLoading">
                    <img width="300" v-if="state.formState.coverPicture" :src="state.formState.coverPicture" alt="avatar" />
                    <div v-else>
                      <plus-outlined></plus-outlined>
                      <div class="ant-upload-text">{{ t('message-manage.label.upload') }}</div>
                    </div>
                  </a-spin>
                </a-upload>
                <div class="upload-title">{{ t('message-manage.message.uploadMessage') }}</div>
              </a-form-item>

              <a-form-item :label="t('message-manage.title.messageLabel')"
                           :rules="{required: true, message: t('message-manage.placeholder.pleaseSelect'), trigger: 'blur'}"
                           name="coverType"
              >
                  <a-select v-model:value="state.formState.coverType" :placeholder="t('message-manage.placeholder.pleaseSelect')">
                  <a-select-option v-for="item in dictLists.data[dictEnum.MESSAGE_TYPE]"
                                   :value="item.value"
                                   :key="item.id"
                  >{{item.label}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item :label="t('message-manage.title.releaseTime')"
                           :rules="[
                             {required: true, message: t('message-manage.placeholder.pleaseSelect'), trigger: 'change', type: 'object'}
                           ]"
                           name="releaseTime"
              >
                <a-date-picker
                  v-model:value="state.formState.releaseTime"
                  show-time
                  type="date"
                  :placeholder="t('message-manage.placeholder.pleaseSelect')"
                  style="width: 100%"
                />
              </a-form-item>
              <a-form-item :label="t('message-manage.title.title')"
                           :rules="{required: true, message: t('message-manage.placeholder.pleaseEnter'), trigger: 'blur'}"
                           name="title"
              >
                <a-input v-model:value="state.formState.title"
                         :placeholder="t('message-manage.placeholder.pleaseSelect')"
                />
              </a-form-item>

              <a-form-item :label="t('message-manage.label.content')"
                           :rules="{required: true, message: t('message-manage.placeholder.pleaseSelect'), trigger: 'change'}"
                           :wrapper-col="{span: 24}"
                           name="consultationContent"
              >
                <TinyMCE v-model:value="state.formState.consultationContent" />
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
    </page-layout>
  </div>
</template>

<script>
import TinyMCE from '@/component/tinymce'
import {defineComponent, reactive, toRaw, ref, onMounted} from 'vue'
import { message } from 'ant-design-vue'
import { upload } from "@/api/module/oss"
import { getDictByCodesReturnObj } from '@/tools/get-dict'
import dictEnum from '@/const/dict'
import { save, selectById } from "@/api/module/message"
import moment from 'moment'
import {useRoute, useRouter} from "vue-router"
import { isEmpty } from '@/tools/common'
import {update} from "../../../api/module/message"
import { useI18n } from 'vue-i18n'
import mixin from '@/mixins'

export default defineComponent({
  name: "message-manage-add",
  components: {
    TinyMCE
  },
  setup() {
    const { returnRoute } = mixin.setup()
    const { t } = useI18n()
    const router = useRouter()
    const route = useRoute()
    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref('');
    const formRef = ref()
    let dictLists = reactive({
      data: {}
    })
    const state = reactive({
      buttons: [
        {
          name: 'save',
          event: () => onSubmit(),
          type: "primary",
          code: ''
        },
        {
          name: 'reset',
          event: () => resetForm(),
          code: ''
        }
      ],
      uploadImgLoading: false,
      formState: {
        title: '',
        coverType: undefined,
        releaseTime: null,
        delivery: false,
        consultationContent: '',
        coverPicture: ''
      }
    })

    onMounted(async () => {
      resetForm()
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.MESSAGE_TYPE,
      ])
      if (!isEmpty(route.query.id)) {
        const result = await selectById({id: route.query.id})
        if (result.code === 500) return message.error(result.msg || t('message-manage.message.errorMessage'))
        state.formState = {
          ...state.formState,
          ...result.data,
          releaseTime: result.data.releaseTime ? moment(result.data.releaseTime).format('YYYY-MM-DD HH:mm:ss') : null
        }
      }
    })

    const resetForm = () => {
      formRef.value.resetFields()
    }

    const onSubmit = () => {
      formRef.value.validate().then(() => {
        if (route.query.id) {
          updateItem({
            ...toRaw(state.formState),
            releaseTime: moment(state.formState.releaseTime).format('YYYY-MM-DD HH:mm:ss')
          })
        } else {
          addItem({
            ...toRaw(state.formState),
            releaseTime: moment(state.formState.releaseTime).format('YYYY-MM-DD HH:mm:ss')
          })
        }
      })
    };

    const addItem = (data) => {
      save(data).then(res => {
        if (res.code === 200) {
          message.success(t('message-manage.message.addSuccess'));
          returnRoute()
        }
      })
    }

    const updateItem = (data) => {
      update(data).then(res => {
        if (res.code === 200) {
          message.success(t('message-manage.message.editSuccess'));
          returnRoute()
        }
      })
    }

    const beforeUpload = file => {
      if (!state.uploadImgLoading) {
        const Files = new FormData()
        Files.append('file', file)
        state.uploadImgLoading = true
        upload(Files).then(res => {
          if (res.code === 500) {
            message.error({ content: res.msg || t('message-manage.message.uploadErrorMessage') })
          } else {
            const { path: url, id: fileId, remark, name } = res.data
            state.formState.coverPicture = url
          }
          state.uploadImgLoading = false
        }).catch(() => state.uploadImgLoading = false)
      }
      return false
    };

    return {
      state,
      labelCol: {
        span: 2,
      },
      wrapperCol: {
        span: 6,
      },
      onSubmit,
      fileList,
      loading,
      imageUrl,
      beforeUpload,
      dictLists,
      dictEnum,
      formRef,
      route,
      t
    };
  },
})
</script>

<style lang="less" scoped>
.upload-title {
  font-size: 14px;
  color: #b7b7b7;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
